//
//  ChartTheme.swift
//  Charts
//
//  Created by symbio on 2023/3/7.
//

import Foundation
import CMSUIComponents

extension NSUIColor {
    func cms_themeValue(for useTheme: Bool? = false) -> NSUIColor {
        return newValue(forTheme: useTheme ?? false)
    }
}

extension NSAttributedString {
    func cms_themeValue(for useTheme: Bool? = false) -> NSAttributedString {
        return newValue(forTheme: useTheme ?? false)
    }
    
    func draw(with rect: CGRect, options: NSStringDrawingOptions = [], context: NSStringDrawingContext?, cgcontext: CGContext?) {
        cms_themeValue(for: cgcontext?.useTheme).draw(with: rect, options: options, context: context)
    }
}

extension NSDictionary {
    func cms_themeValue(for useTheme: Bool? = false) -> NSDictionary {
        return newValue(forTheme: useTheme ?? false)
    }
}

extension UIImage {
    func cms_themeValue(for useTheme: Bool? = false) -> UIImage {
        return newValue(forTheme: useTheme ?? false)
    }
}

extension CGContext {
    func setFillColor(_ color: NSUIColor?) {
        if let cgColor = color?.cms_themeValue(for: useTheme).cgColor {
            setFillColor(cgColor)
        }
    }
    
    func setStrokeColor(_ color: NSUIColor?) {
        if let cgColor = color?.cms_themeValue(for: useTheme).cgColor {
            setStrokeColor(cgColor)
        }
    }

    var useTheme: Bool {
        return ChartUtils.value(for: self) as? Bool ?? false
    }
}

extension UIImage {
    func draw(in rect: CGRect, context: CGContext?) {
        cms_themeValue(for: context?.useTheme).draw(in: rect)
    }
}

extension NSString {

    func draw(at point: CGPoint, withAttributes attrs: [NSAttributedString.Key : Any]? = nil, context: CGContext?) {
        draw(at: point, withAttributes: (attrs as? NSDictionary)?.cms_themeValue(for: context?.useTheme) as? [NSAttributedString.Key : Any])
    }
    
    func draw(with rect: CGRect, options: NSStringDrawingOptions = [], attributes: [NSAttributedString.Key : Any]? = nil, context: NSStringDrawingContext?, cgcontext: CGContext?) {
        draw(with: rect,options: options, attributes: (attributes as? NSDictionary)?.cms_themeValue(for: cgcontext?.useTheme) as? [NSAttributedString.Key : Any], context: context)
    }
}

func NSUIGraphicsGetCurrentContext(_ view: UIView?) -> CGContext?
{
    let context = UIGraphicsGetCurrentContext()
    if let view = view {
        ChartUtils.setValue(for: context, value:  view.cms_curThemeState == .support)
    }
    return context
}

